import express, { Request, Response, Router } from 'express';
import { PrismaClient } from '@prisma/client';
import { authMiddleware } from '../middleware/auth';
import { ApiResponse } from '../utils/response';

const router: Router = express.Router();
const prisma = new PrismaClient();

// 获取推荐人信息
router.get('/info', authMiddleware, async (req: Request, res: Response): Promise<void> => {
  try {
    const userId = (req as any).userId;

    // 获取用户信息
    const user = await prisma.user.findUnique({
      where: { id: userId }
    });

    if (!user) {
      res.status(404).json(ApiResponse.error('사용자를 찾을 수 없습니다.'));
      return;
    }

    // 获取或生成推荐码（使用idNumber）
    let referralCode = user.referralCode;
    if (!referralCode) {
      // 如果没有推荐码，使用idNumber作为推荐码
      referralCode = user.idNumber;
      await prisma.user.update({
        where: { id: userId },
        data: { referralCode }
      });
    }

    const referralLink = `https://my-nearwallet.com/register?referralCode=${referralCode}`;

    // 统计推荐用户数量
    const referredCount = await prisma.user.count({
      where: { referredBy: userId }
    });

    const referralInfo = {
      referralCode,
      referralLink,
      totalReferredCount: Number(referredCount)
    };

    res.json(ApiResponse.success(referralInfo, '추천인 정보 조회에 성공했습니다.'));
  } catch (error) {
    console.error('추천인 정보 조회 오류:', error);
    res.status(500).json(ApiResponse.error('추천인 정보 조회에 실패했습니다.'));
  }
});

// 获取推荐收益
router.get('/earnings', authMiddleware, async (req: Request, res: Response): Promise<void> => {
  try {
    const userId = (req as any).userId;

    // 获取推荐奖励记录
    const referralRewards = await prisma.referralReward.findMany({
      where: { userId }
    });

    const today = new Date();
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);

    // 计算今日和昨日收益
    const todayEarnings = referralRewards
      .filter(r => r.createdAt.toDateString() === today.toDateString())
      .reduce((sum, r) => sum + Number(r.amount), 0);

    const yesterdayEarnings = referralRewards
      .filter(r => r.createdAt.toDateString() === yesterday.toDateString())
      .reduce((sum, r) => sum + Number(r.amount), 0);

    const totalEarnings = referralRewards.reduce((sum, r) => sum + Number(r.amount), 0);

    // 获取质押推荐奖励记录
    const stakingRewards = await prisma.stakingReferralReward.findMany({
      where: { userId }
    });

    // 直接从数据库记录累加NEAR数量（使用充值时的实际NEAR数量）
    const todayStakingNEAR = stakingRewards
      .filter(r => r.createdAt.toDateString() === today.toDateString())
      .reduce((sum, r) => sum + Number(r.amountNear), 0);

    // 历史累计总NEAR数量（所有历史记录的总和）
    const accumulatedStakingNEAR = stakingRewards.reduce((sum, r) => sum + Number(r.amountNear), 0);

    // 获取用户当前的lockedAmount（可用的推荐收益余额）
    const userStaking = await prisma.userStaking.findUnique({
      where: { userId },
      select: { lockedAmount: true }
    });

    // 使用lockedAmount作为当前可用的推荐收益总额
    const availableStakingNEAR = userStaking ? Number(userStaking.lockedAmount) : 0;

    const earnings = {
      earnings: {
        yesterday: yesterdayEarnings,
        today: todayEarnings,
        total: totalEarnings
      },
      stakingEarnings: {
        accumulated: accumulatedStakingNEAR,  // 历史累计总额
        today: todayStakingNEAR,
        total: availableStakingNEAR  // 返回当前可用的NEAR余额
      }
    };

    res.json(ApiResponse.success(earnings, '추천 수익 조회에 성공했습니다.'));
  } catch (error) {
    console.error('추천 수익 조회 오류:', error);
    res.status(500).json(ApiResponse.error('추천 수익 조회에 실패했습니다.'));
  }
});

// 获取推荐用户列表
router.get('/users', authMiddleware, async (req: Request, res: Response): Promise<void> => {
  try {
    const userId = (req as any).userId;
    const { page = 1, limit = 20 } = req.query;

    const referredUsers = await prisma.user.findMany({
      where: { referredBy: userId },
      select: {
        id: true,
        username: true,
        name: true,
        idNumber: true,
        createdAt: true
      },
      orderBy: { createdAt: 'desc' },
      skip: (Number(page) - 1) * Number(limit),
      take: Number(limit)
    });

    const totalCount = await prisma.user.count({
      where: { referredBy: userId }
    });

    const users = referredUsers.map(user => ({
      id: user.id.toString(),
      name: user.name || user.username || `사용자 ${user.id}`,
      idNumber: user.idNumber,
      registrationDate: user.createdAt.toISOString().split('T')[0]
    }));

    res.json(ApiResponse.success({
      users,
      pagination: {
        page: Number(page),
        limit: Number(limit),
        total: Number(totalCount)
      }
    }, '추천 사용자 목록 조회에 성공했습니다.'));
  } catch (error) {
    console.error('추천 사용자 목록 조회 오류:', error);
    res.status(500).json(ApiResponse.error('추천 사용자 목록 조회에 실패했습니다.'));
  }
});

// 搜索推荐用户
router.get('/search', authMiddleware, async (req: Request, res: Response): Promise<void> => {
  try {
    const userId = (req as any).userId;
    const { query } = req.query;

    if (!query) {
      // 如果没有搜索条件，返回所有用户
      const allUsers = await prisma.user.findMany({
        where: { referredBy: userId },
        select: {
          id: true,
          username: true,
          name: true,
          idNumber: true,
          createdAt: true
        },
        orderBy: { createdAt: 'desc' }
      });

      const users = allUsers.map(user => ({
        id: user.id.toString(),
        name: user.name || user.username || `사용자 ${user.id}`,
        idNumber: user.idNumber,
        registrationDate: user.createdAt.toISOString().split('T')[0]
      }));

      res.json(ApiResponse.success(users, '추천 사용자 검색에 성공했습니다.'));
      return;
    }

    const searchTerm = query.toString().toLowerCase();

    const referredUsers = await prisma.user.findMany({
      where: {
        referredBy: userId,
        OR: [
          { username: { contains: searchTerm } },
          { name: { contains: searchTerm } },
          { id: isNaN(Number(searchTerm)) ? undefined : Number(searchTerm) }
        ]
      },
      select: {
        id: true,
        username: true,
        name: true,
        idNumber: true,
        createdAt: true
      },
      orderBy: { createdAt: 'desc' }
    });

    const users = referredUsers.map(user => ({
      id: user.id.toString(),
      name: user.name || user.username || `사용자 ${user.id}`,
      idNumber: user.idNumber,
      registrationDate: user.createdAt.toISOString().split('T')[0]
    }));

    res.json(ApiResponse.success(users, '추천 사용자 검색에 성공했습니다.'));
  } catch (error) {
    console.error('추천 사용자 검색 오류:', error);
    res.status(500).json(ApiResponse.error('추천 사용자 검색에 실패했습니다.'));
  }
});

// 提交推荐收益提现申请
router.post('/withdraw/request', authMiddleware, async (req: Request, res: Response): Promise<void> => {
  try {
    const userId = (req as any).userId;
    const { amountKrw } = req.body;

    // 验证提现金额
    if (!amountKrw || isNaN(parseFloat(amountKrw)) || parseFloat(amountKrw) <= 0) {
      res.status(400).json(ApiResponse.error('출금 금액은 0보다 커야 합니다.'));
      return;
    }

    const withdrawAmountKrw = parseFloat(amountKrw);

    // 检查最小提现金额限制
    if (withdrawAmountKrw < 10000) {
      res.status(400).json(ApiResponse.error('최소 출금 금액은 10,000원 입니다.'));
      return;
    }

    // 获取用户信息
    const user = await prisma.user.findUnique({
      where: { id: userId },
      include: {
        stakingInfo: true
      }
    });

    if (!user) {
      res.status(404).json(ApiResponse.error('사용자를 찾을 수 없습니다.'));
      return;
    }

    // 获取当前NEAR价格
    const { priceService } = await import('../services/priceService');
    const nearPrice = await priceService.getNearPrice();

    // 计算需要的NEAR数量
    const requiredNear = withdrawAmountKrw / nearPrice;

    // 检查用户的lockedAmount是否足够
    if (!user.stakingInfo) {
      res.status(400).json(ApiResponse.error('추천 수익이 없습니다.'));
      return;
    }

    const availableLockedNear = Number(user.stakingInfo.lockedAmount);
    if (availableLockedNear < requiredNear) {
      res.status(400).json(ApiResponse.error(
        `사용 가능한 추천 수익이 부족합니다. ` +
        `현재 사용 가능: ${availableLockedNear.toFixed(4)} NEAR (약 ${(availableLockedNear * nearPrice).toLocaleString('ko-KR')}원)`
      ));
      return;
    }

    // 检查是否有待处理的提现申请
    const pendingWithdraw = await prisma.referralWithdrawRecord.findFirst({
      where: {
        userId,
        status: 'PENDING'
      }
    });

    if (pendingWithdraw) {
      res.status(400).json(ApiResponse.error('처리되지 않은 출금 신청이 있습니다. 관리자 검토를 기다려 주세요.'));
      return;
    }

    // 创建提现记录
    await prisma.$transaction(async (tx) => {
      // 创建提现申请
      const withdrawRecord = await tx.referralWithdrawRecord.create({
        data: {
          userId,
          amountKrw: withdrawAmountKrw,
          amountNear: requiredNear,
          nearPrice: nearPrice,
          bankAccount: user.withdrawalAccount,
          bankName: user.withdrawalBank,
          accountHolder: user.accountHolder,
          status: 'PENDING'
        }
      });

      // 冻结对应的lockedAmount（从lockedAmount中扣除，确保用户不能重复申请）
      await tx.userStaking.update({
        where: { userId },
        data: {
          lockedAmount: { decrement: requiredNear }
        }
      });

      return withdrawRecord;
    });

    res.json(ApiResponse.success({
      amountKrw: withdrawAmountKrw,
      amountNear: requiredNear,
      nearPrice
    }, '출금 신청이 접수되었습니다. 관리자 검토를 기다려 주세요.'));
  } catch (error) {
    console.error('추천 수익 출금 신청 오류:', error);
    res.status(500).json(ApiResponse.error('출금 신청에 실패했습니다. 잠시 후 다시 시도해 주세요.'));
  }
});

// 获取推荐收益提现历史记录
router.get('/withdraw/history', authMiddleware, async (req: Request, res: Response): Promise<void> => {
  try {
    const userId = (req as any).userId;
    const { page = 1, limit = 20, status } = req.query;

    // 构建查询条件
    const where: any = { userId };
    if (status && status !== 'all') {
      where.status = status as string;
    }

    // 获取提现记录
    const withdrawals = await prisma.referralWithdrawRecord.findMany({
      where,
      select: {
        id: true,
        amountKrw: true,
        amountNear: true,
        nearPrice: true,
        status: true,
        bankAccount: true,
        bankName: true,
        accountHolder: true,
        adminNote: true,
        createdAt: true,
        processedAt: true
      },
      orderBy: { createdAt: 'desc' },
      skip: (Number(page) - 1) * Number(limit),
      take: Number(limit)
    });

    // 获取总记录数
    const total = await prisma.referralWithdrawRecord.count({ where });

    // 统计各状态的数量
    const statusCounts = await prisma.referralWithdrawRecord.groupBy({
      by: ['status'],
      where: { userId },
      _count: {
        status: true
      }
    });

    const summary = {
      pending: Number(statusCounts.find(s => s.status === 'PENDING')?._count.status) || 0,
      confirmed: Number(statusCounts.find(s => s.status === 'CONFIRMED')?._count.status) || 0,
      failed: Number(statusCounts.find(s => s.status === 'FAILED')?._count.status) || 0,
      cancelled: Number(statusCounts.find(s => s.status === 'CANCELLED')?._count.status) || 0
    };

    res.json(ApiResponse.success({
      records: withdrawals.map(w => ({
        ...w,
        amountKrw: Number(w.amountKrw),
        amountNear: Number(w.amountNear),
        nearPrice: Number(w.nearPrice)
      })),
      summary,
      pagination: {
        page: Number(page),
        limit: Number(limit),
        total: Number(total),
        totalPages: Math.ceil(Number(total) / Number(limit))
      }
    }));
  } catch (error) {
    console.error('추천 수익 출금 내역 조회 오류:', error);
    res.status(500).json(ApiResponse.error('출금 내역 조회에 실패했습니다.'));
  }
});

export default router;
